<?php

namespace control;

//管理员后台-收发汇总表
class receiptDeliverySummaryClass extends adIndexClass
{
    private const title = '收发汇总表';
    private const page  = 'receiptDeliverySummary';
    private const table = 'inventory_record';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'code'           => [
                        'name'  => '{l.receiptDeliverySummary.homeSearch.code}',
                        'width' => 150,
                    ],
                    'name'           => [
                        'name'  => '{l.receiptDeliverySummary.homeSearch.name}',
                        'width' => 150,
                    ],
                    'typeName'       => [
                        'name'  => '{l.receiptDeliverySummary.homeSearch.materialType}',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '{l.receiptDeliverySummary.homeSearch.model}',
                        'width' => 150,
                    ],
                    'unit'           => [
                        'name'  => '{l.receiptDeliverySummary.homeSearch.unit}',
                        'width' => 60,
                    ],
                    'warehouseId'    => [
                        'name'  => '{l.receiptDeliverySummary.homeSearch.warehouse}',
                        'width' => 100,
                    ],
                    'defaultNum'      => [
                        'name'  => '{l.receiptDeliverySummary.homeSearch.default}',
                        'width' => 100,
                    ],
                    'defaultMoney'   => [
                        'name'  => '期初金额',
                        'width' => 100,
                    ],
                    'inNum'          => [
                        'name'  => '{l.receiptDeliverySummary.homeSearch.inNum}',
                        'width' => 100,
                    ],
                    'inPrice'        => [
                        'name'  => '{l.receiptDeliverySummary.homeSearch.inPrice}',
                        'width' => 100,
                    ],
                    'inMoney'        => [
                        'name'  => '{l.receiptDeliverySummary.homeSearch.inMoney}',
                        'width' => 100,
                    ],
                    'outNum'         => [
                        'name'  => '{l.receiptDeliverySummary.homeSearch.outNum}',
                        'width' => 100,
                    ],
                    'outPrice'       => [
                        'name'  => '{l.receiptDeliverySummary.homeSearch.outPrice}',
                        'width' => 100,
                    ],
                    'outMoney'       => [
                        'name'  => '{l.receiptDeliverySummary.homeSearch.outMoney}',
                        'width' => 100,
                    ],
                    'inventoryNum'   => [
                        'name'  => '期末库存',
                        'width' => 100,
                    ],
                    'inventoryPrice' => [
                        'name'  => '{l.receiptDeliverySummary.homeSearch.inventoryPrice}',
                        'width' => 100,
                    ],
                    'inventoryMoney' => [
                        'name'  => '{l.receiptDeliverySummary.homeSearch.inventoryMoney}',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('receiptDeliverySummary.home.orderDate')    => text(['name' => 'orderDate', 'laydate' => ['range' => '~', 'type' => 'date']]),
                    L('receiptDeliverySummary.home.code')         => text(array("name" => "code")),
                    L('receiptDeliverySummary.home.materialName') => text(array("name" => "materialName")),
                ],
                [
                    L('inventoryDistribution.home.type')       => materialClass::typeSelect(name: 'typeId', title: '请选择'),
                    L('receiptDeliverySummary.home.warehouse') => selectMultiple([
                        'table'    => 'warehouse',
                        'sqlField' => 'name',
                        'sqlId'    => 'id',
                        'where'    => "coid = '" . self::$coid . "' AND state = '启用' " . self::getWarehouseSql(),
                        'name'     => 'warehouseId',
                        'class'    => 'width200'
                    ]),
                ]
            ]
        ], 1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 查询条件
     *
     * @return string
     */
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'" . self::page . "'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /**
     * 列表页-查询结果
     *
     * @return string
     */
    public function homeSearch(): string
    {
        //查询结果

        $where      = " coid = '" . self::$coid . "' ";
        $whereTotal = "";
        $mwhere     = search([
            "like" => [
                'code'     => $this->post('code'),
                'name'     => $this->post('materialName'),
                'typePath' => $this->post('typeId'),
            ],
        ]);
        if ($mwhere) {
            $where      .= " AND materialId IN (SELECT id FROM material WHERE coid = '" . self::$coid . "' $mwhere )  ";
            $whereTotal .= " AND materialId IN (SELECT id FROM material WHERE coid = '" . self::$coid . "' $mwhere )  ";
        }
        $where      .= search([
            '=' => [
                'warehouseId' => $this->post('warehouseId'),
            ],
        ]);
        $whereTotal .= search([
            '=' => [
                'mx.warehouseId' => $this->post('warehouseId'),
            ],
        ]);
        $where      .= self::getWarehouseSql('warehouseId');
        $whereTotal .= self::getWarehouseSql('mx.warehouseId');

        $where          .= " and coid = '" . self::$coid . "' ";
        $orderDate      = $this->post('orderDate');
        $startDate      = '';
        $endDate        = '';
        $inventoryWhere = "";
        if ($orderDate) {
            $inventoryWhere = self::timeComparison($orderDate, 'date', 'confirmTime');
            $data           = explode('~', $orderDate);
            $startDate      = trim($data[0]);
            $endDate        = trim(end($data));
        }
        $fieldArr = self::resolveField([
            'field' => ' `id`, `coid`, `warehouseId`, `materialId`, `time` ',
            'group' => 'materialId, warehouseId',
        ]);
        //排序
        $orderBy                     = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'time',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        $where                       .= $fieldArr['group'];
        $page                        = $this->page([
            "table" => self::table,
            'field' => $fieldArr['field'],
            "where" => $where,
            "order" => $orderBy['orderBy']
        ]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $material     = query('material', " id = '$array[materialId]'", "id,typeId,typeName,unit,code,name,model,model");
            $defaultNum   = 0;
            $defaultMoney = 0;
            if (!empty($startDate)) {
                $openingIn    = find(array(
                    "table"  => "inventory_changes_detail as mx join inventory_changes as inv on mx.orderId = inv.id",
                    "field"  => " ifnull(sum(mx.num),0) as num,ifnull(sum(mx.money),0) as money ",
                    "single" => " 1=1 and mx.coid = '" . self::$coid . "' and inv.state in ('已入库','已复核') and inv.classify = 1 and mx.materialId = '" . $array['materialId'] . "' and mx.warehouseId = '" . $array['warehouseId'] . "' and date_format(confirmTime, '%Y-%m-%d') < '$startDate' "
                ));
                $openingOut   = find(array(
                    "table"  => "inventory_changes_detail as mx join inventory_changes as inv on mx.orderId = inv.id",
                    "field"  => " ifnull(sum(mx.num),0) as num,ifnull(sum(mx.money),0) as money ",
                    "single" => " 1=1 and mx.coid = '" . self::$coid . "' and inv.state in ('已出库','已复核') and inv.classify = 0 and mx.materialId = '" . $array['materialId'] . "' and mx.warehouseId = '" . $array['warehouseId'] . "' and date_format(confirmTime, '%Y-%m-%d') < '$startDate' "
                ));
                $defaultNum   = $openingIn['num'] - $openingOut['num'];
                $defaultMoney = $openingIn['money'] - $openingOut['money'];
            }
            $in = find(array(
                "table"  => "inventory_changes_detail as mx join inventory_changes as inv on mx.orderId = inv.id",
                "field"  => " ifnull(sum(mx.num),0) as num,ifnull(sum(mx.money),0) as money ",
                "single" => " 1=1 and mx.coid = '" . self::$coid . "' and inv.state in ('已入库','已复核') and inv.classify = 1 and mx.materialId = '" . $array['materialId'] . "' and mx.warehouseId = '" . $array['warehouseId'] . "' {$inventoryWhere} "
            ));

            $out            = find(array(
                "table"  => "inventory_changes_detail as mx join inventory_changes as inv on mx.orderId = inv.id",
                "field"  => " ifnull(sum(mx.num),0) as num,ifnull(sum(mx.money),0) as money ",
                "single" => " 1=1 and mx.coid = '" . self::$coid . "' and inv.state in ('已出库','已复核') and inv.classify = 0 and mx.materialId = '" . $array['materialId'] . "' and mx.warehouseId = '" . $array['warehouseId'] . "' {$inventoryWhere} "
            ));
            $inventoryNum   = $defaultNum + $in['num'] - $out['num'];
            $inventoryMoney = $defaultMoney + $in['money'] - $out['money'];
            $inventoryPrice = self::formattingFigure($inventoryNum == 0 ? 0 : $inventoryMoney / $inventoryNum);
            //$inventoryPrice = inventoryDefaultClass::getInventoryPrice($array['materialId'],$material['unit'],$endDate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'warehouseId':
                        $row[] = warehouseClass::getName($array['warehouseId']);
                        break;
                    case 'code':
                    case 'name':
                    case 'typeName':
                    case 'model':
                    case 'unit':
                    case 'unit_one':
                    case 'unit_two':
                        $row[] = $material[$key];
                        break;
                    case 'defaultNum':
                        $row[] = self::formattingFigure($defaultNum, 'numPrecision');
                        break;
                    case 'defaultMoney':
                        $row[] = self::lostZero($defaultMoney);
                        break;
                    case 'inNum':
                        $row[] = self::lostZero($in['num'], 'numPrecision');
                        break;
                    case 'inPrice':
                        $row[] = $in['num'] > 0 ? self::formattingFigure($in['money'] / $in['num']) : 0;
                        break;
                    case 'inMoney':
                        $row[] = self::lostZero($in['money'], 'pricePrecision');
                        break;
                    case 'outNum':
                        $row[] = self::lostZero($out['num'], 'numPrecision');
                        break;
                    case 'outPrice':
                        $row[] = $out['num'] > 0 ? self::formattingFigure($out['money'] / $out['num']) : 0;
                        break;
                    case 'outMoney':
                        $row[] = self::lostZero($out['money'], 'pricePrecision');
                        break;
                    case 'inventoryNum':
                        $row[] = self::formattingFigure($inventoryNum, 'numPrecision');
                        break;
                    case 'inventoryPrice':
                        $row[] = $inventoryPrice;
                        break;
                    case 'inventoryMoney':
                        $row[] = self::formattingFigure($inventoryMoney);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //期初库存金额
        $inMoney = find(array(
            "table"  => "inventory_changes_detail as mx join inventory_changes as inv on mx.orderId = inv.id",
            "field"  => " ifnull(sum(mx.money),0) as money ",
            "single" => " 1=1 and mx.coid = '" . self::$coid . "' and inv.state in ('已入库','已复核') and inv.classify = 1 and date_format(inv.confirmTime, '%Y-%m-%d') < '$startDate' {$whereTotal} "
        ))['money'];

        $outMoney          = find(array(
            "table"  => "inventory_changes_detail as mx join inventory_changes as inv on mx.orderId = inv.id",
            "field"  => " ifnull(sum(mx.money),0) as money ",
            "single" => " 1=1 and mx.coid = '" . self::$coid . "' and inv.state in ('已出库','已复核') and inv.classify = 0 and date_format(inv.confirmTime, '%Y-%m-%d') < '$startDate' {$whereTotal} "
        ))['money'];
        $putInMoney        = find(array(
            "table"  => "inventory_changes_detail as mx join inventory_changes as inv on mx.orderId = inv.id",
            "field"  => " ifnull(sum(mx.money),0) as money ",
            "single" => " 1=1 and mx.coid = '" . self::$coid . "' and inv.state in ('已入库','已复核') and inv.classify = 1 {$inventoryWhere} {$whereTotal} "
        ))['money'];
        $putOutMoney       = find(array(
            "table"  => "inventory_changes_detail as mx join inventory_changes as inv on mx.orderId = inv.id",
            "field"  => " ifnull(sum(mx.money),0) as money ",
            "single" => " 1=1 and mx.coid = '" . self::$coid . "' and inv.state in ('已出库','已复核') and inv.classify = 0 {$inventoryWhere} {$whereTotal} "
        ))['money'];
        $terminalInventory = $inMoney - $outMoney + $putInMoney - $putOutMoney;
        /*$button.=saleIncomeClass::titleSpan('期初金额合计',self::lostZero($inMoney-$outMoney));
        $button.=saleIncomeClass::titleSpan('入库金额合计',self::lostZero($putInMoney));
        $button.=saleIncomeClass::titleSpan('出库金额合计',self::lostZero($putOutMoney));
        $button.=saleIncomeClass::titleSpan('期末金额合计',self::lostZero($terminalInventory));*/
        $total = [
            'defaultMoney'   => self::lostZero($inMoney - $outMoney),
            'inMoney'        => self::lostZero($putInMoney),
            'outMoney'       => self::lostZero($putOutMoney),
            'inventoryMoney' => self::lostZero($terminalInventory),
        ];
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $orderDate      = $this->get('orderDate');
        $templateId     = $this->get('templateId');
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data           = [];
            $inventoryWhere = '';
            $startDate      = $this->date;
            $endDate        = $this->date;
            if ($orderDate) {
                $inventoryWhere = self::timeComparison($orderDate, 'date', 'confirmTime');
                $data           = explode('~', $orderDate);
                $startDate      = trim($data[0]);
                $endDate        = trim(end($data));
            }
            /***********标题**********/
            $title        = [];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']) {
                    $title[] = $array['aliasName'];
                }
            }
            $sql    = $_SESSION[self::page]['sql'];
            $result = sqlFind($sql);
            //导出数据生成
            foreach ($result as $array) {
                $column       = [];
                $material     = query('material', " id = '$array[materialId]'", "id,typeId,typeName,unit,code,name,model,model");
                $defaultNum   = 0;
                $defaultMoney = 0;
                if (!empty($startDate)) {
                    $openingIn    = find(array(
                        "table"  => "inventory_changes_detail as mx join inventory_changes as inv on mx.orderId = inv.id",
                        "field"  => " ifnull(sum(mx.num),0) as num,ifnull(sum(mx.money),0) as money ",
                        "single" => " 1=1 and mx.coid = '" . self::$coid . "' and inv.state in ('已入库','已复核') and inv.classify = 1 and mx.materialId = '" . $array['materialId'] . "' and mx.warehouseId = '" . $array['warehouseId'] . "' and date_format(confirmTime, '%Y-%m-%d') < '$startDate' "
                    ));
                    $openingOut   = find(array(
                        "table"  => "inventory_changes_detail as mx join inventory_changes as inv on mx.orderId = inv.id",
                        "field"  => " ifnull(sum(mx.num),0) as num,ifnull(sum(mx.money),0) as money ",
                        "single" => " 1=1 and mx.coid = '" . self::$coid . "' and inv.state in ('已出库','已复核') and inv.classify = 0 and mx.materialId = '" . $array['materialId'] . "' and mx.warehouseId = '" . $array['warehouseId'] . "' and date_format(confirmTime, '%Y-%m-%d') < '$startDate' "
                    ));
                    $defaultNum   = $openingIn['num'] - $openingOut['num'];
                    $defaultMoney = $openingIn['money'] - $openingOut['money'];
                }
                $in = find(array(
                    "table"  => "inventory_changes_detail as mx join inventory_changes as inv on mx.orderId = inv.id",
                    "field"  => " ifnull(sum(mx.num),0) as num,ifnull(sum(mx.money),0) as money ",
                    "single" => " 1=1 and mx.coid = '" . self::$coid . "' and inv.state in ('已入库','已复核') and inv.classify = 1 and mx.materialId = '" . $array['materialId'] . "' and mx.warehouseId = '" . $array['warehouseId'] . "' {$inventoryWhere} "
                ));

                $out            = find(array(
                    "table"  => "inventory_changes_detail as mx join inventory_changes as inv on mx.orderId = inv.id",
                    "field"  => " ifnull(sum(mx.num),0) as num,ifnull(sum(mx.money),0) as money ",
                    "single" => " 1=1 and mx.coid = '" . self::$coid . "' and inv.state in ('已出库','已复核') and inv.classify = 0 and mx.materialId = '" . $array['materialId'] . "' and mx.warehouseId = '" . $array['warehouseId'] . "' {$inventoryWhere} "
                ));
                $inventoryNum   = $defaultNum + $in['num'] - $out['num'];
                $inventoryMoney = $defaultMoney + $in['money'] - $out['money'];
                $inventoryPrice = self::formattingFigure($inventoryNum == 0 ? 0 : $inventoryMoney / $inventoryNum);
                foreach ($tempFieldAll as $templateField) {
                    if ($templateField['display']) {
                        $column[] = match ($templateField['columnName']) {
                            '物料编码' => $material['code'],
                            '物料名称' => $material['name'],
                            '物料分类' => $material['typeName'],
                            '规格型号' => $material['model'],
                            '主单位' => $material['unit'],
                            '仓库' => warehouseClass::getName($array['warehouseId']),
                            '期初数量' => self::formattingFigure($defaultNum, 'numPrecision'),
                            '期初金额' => self::formattingFigure($defaultMoney),
                            '入库数量' => self::lostZero($in['num'], 'numPrecision'),
                            '入库单价' => $in['num'] > 0 ? self::formattingFigure($in['money'] / $in['num']) : 0,
                            '入库金额' => self::lostZero($in['money'], 'pricePrecision'),
                            '出库数量' => self::lostZero($out['num'], 'numPrecision'),
                            '出库单价' => $out['num'] > 0 ? self::formattingFigure($out['money'] / $out['num']) : 0,
                            '出库金额' => self::lostZero($out['money'], 'pricePrecision'),
                            '期末库存' => self::formattingFigure($inventoryNum, 'numPrecision'),
                            '库存单价' => $inventoryPrice,
                            '库存金额' => self::formattingFigure($inventoryMoney),
                            default => '',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('receiptDeliverySummary.exportData.log'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('receiptDeliverySummary.exportData.fileName') . ".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify = ''): array
    {
        return match ($classify) {
            default => [
                [
                    'columnName' => '物料编码',
                    'aliasName'  => '物料编码',
                ],
                [
                    'columnName' => '物料名称',
                    'aliasName'  => '物料名称',
                ],
                [
                    'columnName' => '物料分类',
                    'aliasName'  => '物料分类',
                ],
                [
                    'columnName' => '规格型号',
                    'aliasName'  => '规格型号',
                ],
                [
                    'columnName' => '主单位',
                    'aliasName'  => '主单位',
                ],
                [
                    'columnName' => '仓库',
                    'aliasName'  => '仓库',
                ],
                [
                    'columnName' => '期初数量',
                    'aliasName'  => '期初数量',
                ],
                [
                    'columnName' => '期初金额',
                    'aliasName'  => '期初金额',
                ],
                [
                    'columnName' => '入库数量',
                    'aliasName'  => '入库数量',
                ],
                [
                    'columnName' => '入库单价',
                    'aliasName'  => '入库单价',
                ],
                [
                    'columnName' => '入库金额',
                    'aliasName'  => '入库金额',
                ],
                [
                    'columnName' => '出库数量',
                    'aliasName'  => '出库数量',
                ],
                [
                    'columnName' => '出库单价',
                    'aliasName'  => '出库单价',
                ],
                [
                    'columnName' => '出库金额',
                    'aliasName'  => '出库金额',
                ],
                [
                    'columnName' => '期末库存',
                    'aliasName'  => '期末库存',
                ],
                [
                    'columnName' => '库存单价',
                    'aliasName'  => '库存单价',
                ],
                [
                    'columnName' => '库存金额',
                    'aliasName'  => '库存金额',
                ],
            ]
        };
    }
}
